<template>
	<view class="historyOrder">
		<view class="header" :style="{ top: stickyTop + 'px' }">
			<scroll-view :show-scrollbar="false" :scroll-left="scrollLeft" scroll-x="true" scroll-with-animation="true"
				:throttle="false" class="scroll-tab">
				<view class="tabs">
					<view :class="['tabs-item', tabIdx == item.id ? 'act' : '']" v-for="(item, index) in typeList"
						:key="index" @click="handleClickTab(item.id, index)">{{ item.text }}</view>
				</view>
			</scroll-view>
			<!-- 历史工单提示 -->
			<view class="historyTips">
				<view class="left"> {{ title }}</view>
				<view class="right" v-if="tabIdx !== -1 && tabIdx !== 6">
					<filterModel :all="false" :orderType="tabIdx" ref="filterModel" :dateOpt="dateObj" :csd="csd"
						:elevatorId="elevatorId" @filterd="filterd" @showFilterChange="showFilterChange">
					</filterModel>
				</view>
			</view>
		</view>

		<view class="orderListMain">
			<view class="" v-if="list.length">
				<view v-if="tabIdx >= 0">
					<view class="content" v-for="(item, index) in list" :key="index">
						<view class="date">
							{{ item.planDate || "" }}
							<view class="line"></view>
						</view>
						<view>
							<order-list v-for="(e, i) in item.dataList" :key="i" :item="e" :tabIdx="tabIdx"
								:parentIdx="index" :childIdx="i" @userMore="handleUserMore" :elevatorId="elevatorId"
								@update="restList()">
							</order-list>
						</view>
					</view>
				</view>

				<view class="all" v-if="tabIdx == -1">
					<view class="year" v-for="(item, index) in list" :key="index">
						<view class="year_item">
							<view class="year_left">
								<view class="yearLabel">
									{{ item.label }}
								</view>
							</view>

							<view class="year_right">
								<view class="list_item" v-for="(e, i) in item.value" :key="i">
									<view class="left">
										<view class="dateName">
											{{ e.label.slice(5, 12).replaceAll("-", "/") }}
										</view>
										<view class="line"></view>
									</view>
									<view class="right">
										<all-order-list v-for="(v, j) in e.value" :key="j" :item="v"
											@userMore="handleUserMore" :elevatorId="elevatorId" @update="restList()">
										</all-order-list>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="more" v-if="tabIdx == -1" @click="handleLoadMore">
					{{ stopQuery ? "- 已经到底了 -" : "点击加载更多" }}
					<!-- <view v-show="isLoadMore"><uni-load-more :status="loadStatus"></uni-load-more></view> -->
				</view>
				<view class="more" v-if="tabIdx != -1">- 已经到底了 -</view>
			</view>

			<view class="empty" v-else>
				<view class="img">
					<image src="@/static/images/default.png"></image>
				</view>
				<view class="text">- 暂无相关数据 -</view>
			</view>
		</view>
	</view>
</template>

<script>
import filterModel from '../filter/index.vue';
import OrderList from '../eleOrderList.vue';
import AllOrderList from './components/allOrder.vue';
// import dayjs from 'dayjs';
// import { getNowTime, getBeforeDate } from '@/utils/utils.js';
// import UniLoadMore from '@/components/uni-load-more/uni-load-more';
import { getUserlistPlan } from '@/apis/workOrder.js';
import { getAbarbeitungPage } from '@/apis/correction.js';
import {
	maintenanceHistoryTasks,
	// maintenanceUnfinished,
	repairHistoryTasks,
	// repairUnfinished,
	partHistoryTasks,
	// partUnfinished,
	// elevtorMantles,
	getElevatorOfRescueInfo,
	getAllPlanList,
} from '@/apis/elevator.js';
// 保养搜索条件
const mSearchForm = {
	startTime: '',
	endTime: '',
	timeliness: [],
	duration: [],
	templateIds: [],
	sign: [],
};
// 维修搜索条件
const wSearchForm = {
	startTime: '',
	endTime: '',
	problemItems: [],
	sign: [],
};
// 配件搜索条件
const pSearchForm = {
	startTime: '',
	endTime: '',
	partsId: [],
	sign: [],
};
// 空数据搜索条件
const emptDate = {
	startTime: '',
	endTime: '',
	value: '',
	planBeginDate: '',
	planEndDate: '',
};
export default {
	components: {
		filterModel,
		OrderList,
		AllOrderList,
	},
	props: {
		// tab的类型,全部,保养,维修,配件,救援
		// tabIdx: {
		//   type: [String, Number],
		// },
		elevatorId: {
			type: String,
		},
		stickyTop: {
			type: Number,
		},
	},
	data() {
		return {
			dateObj: {
				startTime: '',
				endTime: '',
				value: '',
				planBeginDate: '',
				planEndDate: '',
			},
			// 头部展示已完成多少单,通过接口返回展示
			title: '',
			csd: {},
			wxCsd: {},
			pjCsd: {},
			list: [],
			typeList: [
				{ text: '全部', id: -1 },
				{ text: '保养', id: 0 },
				{ text: '维修', id: 1 },
				{ text: '配件', id: 2 },
				{ text: '事务', id: 3 },
				{ text: '质检', id: 4 },
				{ text: '救援', id: 5 },
				{ text: '整改', id: 6 },
			],
			tabIdx: -1,

			curStarDate: new Date().getFullYear(),
			// curEedDate: dayjs().format("YYYY-MM-DD"),
			// 加载样式：more-加载前样式，loading-加载中样式，noMore-没有数据样式
			loadStatus: 'loading',
			isLoadMore: false,
			stopQuery: false,
			searchForms: {
				current: 1,
				size: 10,
				planStatus: 4,

			},
			scrollLeft: 0,
		};
	},
	created() {
	},
	watch: {

	},
	methods: {
		handleUserMore() {
			// const { parentIdx, childIdx, val } = res;
			// this.list[parentIdx].dataList[childIdx].usermore = val;
		},
		// 首次加载如果为空指标继续加载
		continuereQuest() {
			console.log(this.curStarDate, 'this.curStarDate');
			if (this.curStarDate < 2022) {
				console.log(this.curStarDate);
				this.stopQuery = true;
				return;
			} else {
				this.stopQuery = false;
				this.curStarDate = this.curStarDate - 1;
				console.log('继续加载', this.curStarDate);
				this.fetchOrderList();
			}
		},
		handleLoadMore() {
			if (this.stopQuery) {
				return;
			}
			this.isLoadMore = true;
			this.stopQuery = false;
			this.curStarDate = this.curStarDate - 1;
			this.fetchOrderList();
		},
		// 点击tab页面
		handleClickTab(res, index) {
			this.tabIdx = res;
			this.isLoadMore = false;
			this.curStarDate = new Date().getFullYear();
			this.list = [];
			this.title = '';
			// eslint-disable-next-line vue/custom-event-name-casing
			this.$emit('changeTab');
			if (res !== -1 && res !== 6) {
				// console.log("初始化筛选组件")
				this.csd = {};
				this.dateObj = Object.assign(emptDate, {});
				this.searchForms = {
					current: 1,
					size: 10,
					planStatus: 4,
				};
				this.$nextTick(() => {
					try {
						this.$refs.filterModel.initModel(this.tabIdx, this.dateObj);
					} catch (error) {
						console.log(error);
					}
				});
				wx.createSelectorQuery()
					.in(this)
					.select('.tabs-item')
					.boundingClientRect((data) => {
						let itemWidth = data.width + 8;
						this.scrollLeft = itemWidth * (index - 1);
					})
					.exec();
			}
			this.fetchOrderList();
		},
		resetSearchForm() {
			if (this.tabIdx == 0) {
				this.mSearchForm = Object.assign(mSearchForm, {});
			}
			if (this.tabIdx == 1) {
				this.wSearchForm = Object.assign(wSearchForm, {});
			}
			if (this.tabIdx == 2) {
				this.pSearchForm = Object.assign(pSearchForm, {});
			}
		},
		// 查询列表信息
		fetchOrderList() {
			uni.showLoading({
				title: '加载中',
				mask: true,
			});

			const historyFun = [
				maintenanceHistoryTasks,
				repairHistoryTasks,
				partHistoryTasks,
				getElevatorOfRescueInfo,
				getUserlistPlan,
				getAbarbeitungPage,
			];
			const historyParams = [
				this.mSearchForm,
				this.wSearchForm,
				this.pSearchForm,
				{ type: 2 },
				this.searchForms,
				{ planStatus: 4 }
			];
			if (this.tabIdx >= 0) {
				this.list = [];
				let tindex = [3, 4, 5].includes(this.tabIdx) ? 4 : this.tabIdx == 6 ? 5 : this.tabIdx;
				let objs = {
					elevatorId: this.elevatorId,
					...historyParams[tindex],
				};

				if ([3, 4, 5].includes(this.tabIdx)) {
					if (this.tabIdx === 3) {
						objs.typeStatus = 5;
					}
					if (this.tabIdx === 4) {
						objs.typeStatus = 6;
					}
					if (this.tabIdx === 5) {
						// delete objs.elevatorId
						objs.typeStatus = 3;
					}
					objs.planStatus = this.tabIdx === 5 ? 5 : 4;
				}
				historyFun[tindex](objs).then((res) => {
					if (res) {
						uni.hideLoading();
						const objs = res.data || {};
						let records = [];
						if (this.tabIdx == 6) {
							let list = res.data.records || [];
							const groupedRecords = {};
							list.forEach((record) => {
								record.userNames = record.planFinishUserNames.split(',');
								const date = new Date(record.createTime);
								const year = date.getFullYear();
								const month = (date.getMonth() + 1).toString().padStart(2, '0');
								const planDate = `${year}年${month}月`;

								if (!groupedRecords[planDate]) {
									groupedRecords[planDate] = [];
								}
								groupedRecords[planDate].push(record);
							});

							records = Object.keys(groupedRecords).map((planDate) => ({
								planDate,
								dataList: groupedRecords[planDate],
							}));
						} else {
							this.title = res.data.title;
							records = res.data.list || [];
							records.forEach((item) => {
								for (let i = 0; i < item.dataList.length; i++) {
									item.dataList[i].usermore = false;
									if (item.dataList[i].planDesc) {
										item.dataList[i].planDesc = item.dataList[i].planDesc.replaceAll('&gt;', '>');
									}
									if (item.dataList[i].partsName != null) {
										const parts = item.dataList[i].partsName.split('&amp;&amp;');
										item.dataList[i].parts = parts[parts.length - 1];
									}
								}
							});
						}
						if ([3, 4, 5, 6].includes(this.tabIdx)) {
							this.title = this.tabIdx === 5 ? `已完成救援(${objs.total})` : `已完成任务(${objs.total})`;
						}

						this.list = records;
						console.log('records', records);
						this.isCanScroll = this.list.length ? true : false;
					}
				});
			} else {
				// 这里是全部的数据

				// if (!this.isLoadMore) {
				//   this.list = [];
				//   this.curStarDate = new Date().getFullYear()
				// }
				const parsms = {
					elevatorId: this.elevatorId,
					startDate: this.curStarDate + '-01-01 00:00:00',
					endDate: this.curStarDate + '-12-31 23:59:59',
				};
				getAllPlanList(parsms).then((res) => {
					if (res.data.value.length == 0) {
						// 如果是加载更多
						if (this.isLoadMore) {
							uni.hideLoading();
							this.title = res.data.label;
							this.stopQuery = true;
							return;
						} else {
							// 如果是首次加载
							this.list = [];
							this.continuereQuest();
						}
					}
					this.title = res.data.label;
					res.data.value.forEach(item => {
						item.value.forEach(it => {
							it.value.forEach(j => {
								if (j.planDesc) {
									j.planDesc = j.planDesc.replaceAll('&gt;', '>');
								}
							});
						});
					});
					this.list.push(...res.data.value);
					uni.hideLoading();
				});
			}
		},
		// 接收到的筛选后的数据
		filterd(res) {
			console.log(res, '最外层父组件');
			let {
				choosed,
				dateObj: { startTime, endTime, planBeginDate, planEndDate },
			} = res;
			let dateObj = res.dateObj;
			this.csd = choosed;
			console.log(res, dateObj, '最外层父组件');
			// let map = {
			// 	0: this.mSearchForm,
			// 	1: this.wSearchForm,
			// 	2: this.pSearchForm,
			// };

			if (this.tabIdx == 0) {
				this.mSearchForm = {};
				this.mSearchForm = {
					...choosed,
					startTime,
					endTime,
					planBeginDate,
					planEndDate,
				};
				this.csd = choosed;
				this.dateObj = dateObj;
			} else if (this.tabIdx == 1) {
				this.wSearchForm = {};
				(this.wSearchForm = {
					...choosed,
					startTime,
					endTime,
					planBeginDate,
					planEndDate,
				}),
					(this.dateObj = dateObj);
			} else if ([3, 4, 5].includes(this.tabIdx)) {
				this.searchForms = {};
				(this.searchForms = {
					current: 1,
					size: 10,
					planStatus: 4,
					finishBeginTime: startTime,
					finishEndTime: endTime,
					createBeginTime: planBeginDate,
					createEndTime: planEndDate,
				}),
					(this.dateObj = dateObj);
			} else {
				this.pSearchForm = {};
				(this.pSearchForm = {
					...choosed,
					startTime,
					endTime,
					planBeginDate: planBeginDate,
					planEndDate: planEndDate,
				}),
					(this.dateObj = dateObj);
			}

			this.fetchOrderList();
		},
		showFilterChange(res) {
			this.$emit('showFilterChange', res);
			this.isCanScroll = !res;
		},
	},
};
</script>

<style lang="scss" scoped>
.scroll-tab {
	background-color: #ffffff;
	white-space: nowrap;
	/* 必要，导航栏才能横向*/
	text-align: center;
	// border-bottom: 2rpx solid #eee;
}

.historyOrder {
	.header {
		position: sticky;
		// top: 0;
		left: 0;

		// #ifndef H5 
		z-index: 10;
		// #endif

		// #ifdef H5 
		z-index: 1;
		// #endif
	}

	.tabs {
		width: 145%;
		background-color: #ffffff;
		display: flex;
		// border-bottom: 2rpx #eee solid;
		height: 76rpx;
		padding: 0 22rpx;
		align-items: center;
		// justify-content: space-between;

		&-item {
			display: flex;
			// width: 128rpx;
			margin: 0 16rpx;
			padding: 0 30rpx;
			height: 44rpx;
			background: #f3f6f8;
			border-radius: 22rpx;
			font-size: 26rpx;
			font-weight: 400;
			// border-bottom: 4rpx solid #fff;
			color: #666;
			// transition: 0.4s all;
			justify-content: center;
			align-items: center;
		}

		.act {
			color: #0091ff;
			background: #dcf0ff;
		}
	}

	.historyTips {
		background-color: #f3f6f8;
		color: #666;
		padding: 20rpx;
		display: flex;
		justify-content: space-between;

		.right {
			width: 300rpx;
		}
	}

	.orderListMain {
		background: #f3f6f8;

		.content_Tit {
			display: flex;
			justify-content: space-between;

			.date_count {
				font-size: 24rpx;
				color: #666666;
				margin-right: 20rpx;

				text {
					color: #0091ff;
				}
			}
		}

		.date {
			color: #333;
			font-size: 26rpx;
			font-weight: 600;
			padding-left: 40rpx;
			position: relative;
		}

		.line {
			width: 4rpx;
			height: 22rpx;
			background: #333333;
			position: absolute;
			left: 20rpx;
			top: 8rpx;
		}

		.more {
			width: 100%;
			padding: 30rpx 0;
			text-align: center;
			color: #999999;
			font-size: 24rpx;
		}
	}

	.empty {
		display: flex;
		align-items: center;
		justify-content: center;

		image {
			width: 64rpx;
			height: 64rpx;
		}

		height: 800rpx;
		flex-direction: column;
	}

	.year {
		width: 100%;

		.year_item {
			display: flex;
			position: relative;

			.year_left {
				position: absolute;
				left: 15rpx;
				font-size: 28rpx;
				top: 18rpx;
				display: flex;

				.title {
					color: #666;
					font-size: 26rpx;
					padding-left: 42rpx;
				}
			}

			.year_right {
				display: flex;
				flex-direction: column;
				flex: 1;
				margin-top: 60rpx;
			}
		}
	}

	.list {
		width: 100%;
		position: relative;
	}

	.list_item {
		display: flex;
		width: 100%;
		position: relative;

		.left {
			font-size: 26rpx;
			font-weight: 500;
			width: 110rpx;
			margin-bottom: 20rpx;
			display: flex;
			justify-content: center;
			padding: 20rpx 0;

			.line {
				width: 2rpx;
				height: calc(100% - 94rpx);
				background: #d2dae0;
				position: absolute;
				left: 44rpx;
				margin: 20rpx 0;
				top: 60rpx;
			}
		}

		.right {
			width: 100%;
			// margin: 0 20rpx;
			// background: pink;
		}
	}
}
</style>
